const DATABASE_NAME = 'test_db'
const VERSION = 1
const TABLE = 'test_table'

/**
 * 在 [db]--[tableName]中新增一条记录[data]
 */
function addRecord(db, tableName, data) {
  return new Promise(function (resolve, reject) {
    let request = db.transaction(tableName, 'readwrite').objectStore(tableName).add(data)
    request.onsuccess = function () {
      resolve({
        code: 200,
        msg: 'success',
      })
    }
    request.onerror = function (e) {
      reject({
        code: 0,
        msg: e.target.error,
      })
    }
  })
}

/**
 * 获取 [db]--[tableName]下，主键为 [key] 的某条记录
 */
function getRecord(db, tableName, key) {
  return new Promise(function (resolve, reject) {
    let request = db.transaction(tableName).objectStore(tableName).get(key)
    request.onsuccess = function (e) {
      resolve({
        code: 200,
        msg: 'success',
        data: e.target.result,
      })
    }
    request.onerror = function (e) {
      reject({
        code: 0,
        msg: e.target.error,
      })
    }
  })
}

/**
 * 根据索引所在位置 [index]，获取 [db]--[tableName]下，索引值为 [identify]的某条记录
 */
function getRecordWithIndex(db, tableName, index, identify) {
  return new Promise(function (resolve, reject) {
    let request = db.transaction(tableName, 'readwrite').objectStore(tableName).index(index).get(identify)
    request.onsuccess = function (e) {
      resolve({
        code: 200,
        data: e.target.result,
        msg: 'success',
      })
    }
    request.onerror = function (e) {
      reject({
        code: 0,
        msg: e.target.error,
      })
    }
  })
}

/**
 * 读取 [db]--[tableName] 下的所有记录
 */
function readAllRecord(db, tableName) {
  return new Promise(function (resolve, reject) {
    let objectStore = db.transaction(tableName).objectStore(tableName)
    let records = []
    objectStore.openCursor().onsuccess = function (e) {
      let cursor = e.target.result
      if (cursor) {
        records.push(cursor.value)
        cursor.continue()
      } else {
        resolve({
          code: 200,
          data: records,
          msg: 'success',
        })
      }
    }
    objectStore.openCursor().onerror = function (e) {
      reject({
        code: 0,
        msg: e.target.error,
      })
    }
  })
}

/**
 * 将 [db]--[tableName]中，主键为 [key]的数据为，更新为 [data]
 */
function updateRecord(db, tableName, data, key) {
  return new Promise(function (resolve, reject) {
    let request = db.transaction(tableName, 'readwrite').objectStore(tableName).put(data, key)
    request.onsuccess = function () {
      resolve({
        code: 200,
        msg: 'success',
      })
    }
    request.onerror = function (e) {
      reject({
        code: 0,
        msg: e.target.error,
      })
    }
  })
}

/**
 * 在 [db]--[tableName]下，删除主键为[key]的记录
 */
function deleteRecord(db, tableName, key) {
  return new Promise(function (resolve, reject) {
    let request = db.transaction(tableName, 'readwrite').objectStore(tableName).delete(key)
    request.onsuccess = function () {
      resolve({
        code: 200,
        msg: 'success',
      })
    }
    request.onerror = function (e) {
      reject({
        code: 0,
        msg: e.target.error,
      })
    }
  })
}

/**
 * 获取数据库对象
 */
function getDB(dbName, version) {
  return new Promise(function (resolve, reject) {
    let request = window.indexedDB.open(dbName, version)
    request.onsuccess = function (e) {
      let db = e.target.result
      resolve(db)
    }
    request.onupgradeneeded = function (e) {
      // 初始化数据库
      let db = e.target.result
      if (!db.objectStoreNames.contains(TABLE)) {
        var objectStore = db.createObjectStore(TABLE, { autoIncrement: true })
        // 创建索引
        objectStore.createIndex('name', 'name', { unique: true })
        objectStore.createIndex('email', 'email', { unique: true })
      }
    }
  })
}

getDB(DATABASE_NAME, VERSION).then(db => {
  let data = {
    id: 1,
    name: '张三',
    age: 18,
    email: 'test@168.com',
  }

  addRecord(db, TABLE, data).then(
    res => {
      console.log(res)
    },
    err => {
      console.log(err)
    },
  )

  getRecord(db, TABLE, 1).then(
    res => {
      console.log(res)
    },
    err => {
      console.log(err)
    },
  )

  getRecordWithIndex(db, TABLE, 'email', 'test@168.com').then(
    res => {
      console.log(res)
    },
    err => {
      console.log(err)
    },
  )

  deleteRecord(db, TABLE, 1).then(
    res => {
      console.log(res)
    },
    err => {
      console.log(err)
    },
  )

  readAllRecord(db, TABLE).then(
    res => {
      console.log(res)
    },
    err => {
      console.log(err)
    },
  )

  updateRecord(db, TABLE, { id: 1, name: '小张三', age: 18, email: 'new@168.com' }, 1).then(
    res => {
      console.log(res)
    },
    err => {
      console.log(err)
    },
  )
})
